<template>
    <view :class="{ 'GoodsBar': true, topUp: topUp }" v-if="btnIndex === 1">
        <image :src="goodsThumb" class="img" />
        <view class="btn"
              @click="toGoodsPage">
            切换产品
            <image src="/static/GoodsBarImg/downArrow.png" class="icon" alt="" />
        </view>
        <t-color-picker
                        ref="colorPicker"
                        :onlySpareColor="colorType === 1 || fillType === 1"
                        :color="{ r: 255, g: 255, b: 255, a: 1 }"
                        :spareColor="colorType === 1 ? threadColors : spareColor"
                        :showOk="colorType === 1 || fillType === 1"
                        @confirm="confirm"
                        @close="close" />
        <view class="btn" @click="open(0)"> 颜色 </view>
        <view class="btn" @click="open(1)" v-if="fillType === 0">缝线</view>
        <view class="btn" @click="toGoodsDetail">产品详情</view>
    </view>
</template>
<script>
import designEditorRender from "../../DesignEditor/designEditorRender";
import designerStore from "../../DesignEditor/designerStore";
import get from "lodash/get";
import { autorun, toJS } from "mobx";
import { Color } from "../../myThree/build/three.module";
import editorBarStore from "../editorBarStore";


export default {
    name: "GoodsBar",
    // 数据
    data() {
        return {
            color: { r: 255, g: 255, b: 255, a: 1 },
            btnIndex: -1,
            goodsThumb: '',
            fillType: designerStore.fillType,
            spareColor: undefined, //衣服的可选颜色
            // 缝线的颜色
            threadColors: ["#ffffff", "#B4B5B9", "#000000"].map(hex => {
                const color = new Color(hex);
                return { r: color.r * 255, g: color.g * 255, b: color.b * 255, a: 1 };
            }),
            colorType: 0, // 0是衣服的颜色,  1是缝线的颜色
            topUp: false,
            isInit: true
        }
    },
    // 监听属性

    //方法
    methods: {
        //跳转到产品页面去
        toGoodsPage() {
            Taro.switchTab({ url: '/pages/product/index' });
        },
        open(colorType = 0) {
            this.colorType = colorType;
            // 打开颜色选择器
            this.$refs.colorPicker.open();
        },
        // 颜色面板的回调事件
        confirm(e) {
            console.log("confirm", e);
            // 如果是局部印的话, 每个颜色都有名字的需要带上名字
            const { goodsData } = designerStore;
            if (goodsData) {
                const colors = get(goodsData, ["colors"], []);
                // 修改衣服颜色
                if (this.colorType === 0) {
                    //修改画布上的背景色
                    designEditorRender.background = e.hex;
                    if (this.fillType === 1) {
                        const targetColor = this.findClosestColor(e.hex, colors.map((item) => item.color));
                        const colorName = colors.find((item) => item.color === targetColor)?.cn;
                        console.log('colors', colors);
                        console.log('e.hex', e.hex);
                        console.log('colorName', colorName);
                        designerStore.setDesignColor(colorName, e.hex, true);
                    } else {
                        // 修改数据里面的背景色
                        designerStore.setDesignColor(e.hex, e.hex, e.applyAll);
                    }
                } else if (this.colorType === 1) {
                    // 修改缝线的颜色
                    designerStore.setThreadColor(e.hex);
                }

            }
        },
        close() {
            console.log("close");
        },
        //跳转到产品详情
        toGoodsDetail() {
            const { goodsData } = designerStore;
            if (goodsData) {
                Taro.navigateTo({ url: `/pages/product/detail?id=${goodsData.id}` });
            }
        },
        hexToRgb(hex) {
            const r = parseInt(hex.substring(1, 3), 16);
            const g = parseInt(hex.substring(3, 5), 16);
            const b = parseInt(hex.substring(5, 7), 16);
            return { r, g, b };
        },

        getColorDistance(color1, color2) {
            const dr = color1.r - color2.r;
            const dg = color1.g - color2.g;
            const db = color1.b - color2.b;
            return dr * dr + dg * dg + db * db; // 平方差之和（无需开方）
        },

        findClosestColor(targetHex, colorArray) {
            const targetRgb = this.hexToRgb(targetHex);
            let minDistance = Infinity;
            let closestColor = null;

            for (const color of colorArray) {
                const currentRgb = this.hexToRgb(color);
                const distance = this.getColorDistance(targetRgb, currentRgb);
                if (distance < minDistance) {
                    minDistance = distance;
                    closestColor = color;
                }
            }

            return closestColor;
        }
    },
    // 计算属性


    //安装完成
    mounted() {
        this.dispose = autorun(() => {
            this.btnIndex = editorBarStore.btnIndex;
            this.topUp = (editorBarStore.btnIndex === 1);
        });

        //切换商品时, 更新商品的缩略图和初始颜色
        this.dispose2 = autorun(async () => {
            const { fillType, goodsData } = designerStore;
            await new Promise(resolve => setTimeout(resolve, 30));
            const { goodsThumb, } = designerStore;

            this.goodsThumb = goodsThumb;
            this.fillType = fillType;

            if (goodsData) {
                const colors = toJS(get(goodsData, ["colors"], []));

                // 如果是局部印,就设置初始颜色
                if (this.fillType === 1) {
                    if (this.isInit) {
                        this.isInit = false;
                    } else if (colors[0]) {
                        designerStore.setDesignColor(colors[0].cn, colors[0].color, true);
                    } else {
                    }
                    this.spareColor = colors.map((item) => {
                        const color = new Color(item.color);
                        return { r: color.r * 255, g: color.g * 255, b: color.b * 255, a: 1 };
                    });
                } else if (fillType === 0) {
                    //满版印是没有可选颜色的
                    this.spareColor = undefined;
                }

            }
        }, { delay: 50 });
    },
    //卸载后
    destroyed() {
        this.dispose();
        this.dispose2();
    },
    //页面显示时

    //页面隐藏时

};
</script>


<style scoped lang="scss">
.GoodsBar {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 48px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #ffffff;
    box-shadow: 0px -4px 4px #dfdfdf;
    bottom: calc(env(safe-area-inset-bottom) + 64px);
    padding-top: 4px;

    &.topUp {
        z-index: 1;
    }

    .img {
        width: 48px;
        height: 48px;
    }

    .btn {
        flex: 1;
        text-align: center;
        border-radius: 4px;
        font-size: 16px;
        height: 48px;
        line-height: 48px;
        cursor: pointer;
        white-space: nowrap;

        .icon {
            width: 16px;
            height: 16px;
            vertical-align: middle;
            margin-left: 2px;
        }
    }

}
</style>